package mm.base.dao;

import mm.base.entity.User;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * 用户Dao类
 */
@Repository
public class UserDao extends BaseDao{

    /**
     * 增加用户
     */
    public Integer insert(User user) throws Exception{
        try {
            if(StringUtils.isEmpty(user.getUid())) {
                throw new RuntimeException("用户UID生成无效!!!");
            }
            if(StringUtils.isEmpty(user.getUserName())){
                throw new RuntimeException("用户账号无效!!!");
            }
            if(StringUtils.isEmpty(user.getPassword())){
                throw new RuntimeException("用户密码无效!!!");
            }
            if(StringUtils.isEmpty(user.getNickName())){
                throw new RuntimeException("用户昵称无效!!!");
            }
            String sql = "insert into tb_user (UID, USERNAME, PASSWORD, NICKNAME) values (?, ?, ?, ?)";
            return template.update(sql, user.getUid(), user.getUserName(), user.getPassword(), user.getNickName());
        }catch (Exception e){
            throw new RuntimeException("新增用户失败!!! 以下为具体错误信息：" + e.getMessage());
        }
    }

    /**
     * 根据UID查询用户信息
     */
    public User selectUser(User user) throws Exception{
        try {

            if(StringUtils.isEmpty(user.getUid())) {
                throw new RuntimeException("用户UID无效!!!");
            }

            List list = new ArrayList();
            list.add(user.getUid());
            String sql = "SELECT * FROM tb_user WHERE UID=?";
            return template.queryForObject(sql, list.toArray(), new RowMapper<User> (){
                @Override
                public User mapRow(ResultSet rs, int i) throws SQLException {
                    User user = new User();
                    user.setUid(rs.getString("UID"));
                    user.setUserName(rs.getString("USERNAME"));
                    user.setPassword(rs.getString("PASSWORD"));
                    user.setNickName(rs.getString("NICKNAME"));
                    return user;
                }
            });
        }catch (Exception e){
            throw new RuntimeException("查询用户失败!!! 以下为具体错误信息：" + e.getMessage());
        }
    }
}
